﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using InformationSystem.Service;
using InformationSystem.Entity;

namespace InformationSystem
{
	/// <summary>
	/// Description of AddModule.
	/// </summary>
	public partial class AddModule : Form
	{
		ModuleService moduleService;
		
		Module module;
		
		public AddModule(ModuleService _moduleService)
		{
			InitializeComponent();

			moduleService = _moduleService;
			
			this.Text = "Add Module";
		}
		
		
		public AddModule(ModuleService _moduleService, int id)
		{
			InitializeComponent();

			moduleService = _moduleService;
			
			module = new Module();
			module.id = id;
			
			module = moduleService.query(module);
			tbName.Text = module.name;
			nudCredit.Value = module.credit;
			this.Text = "Modify Module";
			
		}
		void BtSaveClick(object sender, EventArgs e)
		{
			if (tbName.Text == "")
            {
                MessageBox.Show("Please input name");
                return;
            }

            if (nudCredit.Value == 0)
            {
                MessageBox.Show("Please choose credit");
                return;
            }
            
            String name = tbName.Text.Trim();
            
            if(name.Length < 2)
            {
                MessageBox.Show("Please input correct name, at least 2 characters.");
                return;
            }

            String secondChar = name.Substring(1, 1);
            int l = 0;

            if (!Int32.TryParse(secondChar, out l))
            {
                MessageBox.Show("Please input correct name, the second character must be numberic.");
                return;
            }

            if (l < 4 || l > 6)
            {
                MessageBox.Show("Please input correct name, the second character must be 4,5 or 6.");
                return;
            }
            
            if (module == null)
            {
                module = new Module();
            }
            
            module.name = tbName.Text;
            module.credit = Int32.Parse(nudCredit.Value.ToString());
            module.status = 0;
            if (moduleService.addOrUpdate(module))
            {
                MessageBox.Show("save successful");
            }
            else
            {
                MessageBox.Show("save failed");
            }
            
            
		}
		void BtCloseClick(object sender, EventArgs e)
		{
			this.Close();
		}
		
		
	}
}
